import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService, NzModalService, NzUploadFile } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';
import { API_CONFIG } from 'src/app/service/service.module';
import { WorkOrderService } from 'src/app/service/work-order.service';

function getBase64(file: File): Promise<string | ArrayBuffer | null> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.less']
})
export class AddComponent implements OnInit {

  validateForm!: FormGroup;
  imageList: NzUploadFile[] = [];
  previewVisible: boolean = false;
  previewImage: string | undefined = '';
  uploadUrl: string | null = '';
  headers: any | null = null;
  loading = false;


  handlePreview = async (file: NzUploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj!);
    }
    this.previewImage = file.url || file.preview;
    this.previewVisible = true;
  };

  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.msg.error('必须上传一张图片!');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.msg.error('图片必须小于2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };

  handleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        // Get this url from response in real world.
        this.loading = false;
        break;
      case 'error':
        this.msg.error('Network error');
        this.loading = false;
        break;
    }
  }

  submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.status == "VALID") {
      var data = this.validateForm.value;
      data['images'] = JSON.stringify(this.imageList.map(item => { return item.response.name }));
      this.workOrderService.add(data).subscribe(result => {
        this.validateForm.reset();
        for (const key in this.validateForm.controls) {
          this.validateForm.controls[key].markAsPristine();
          this.validateForm.controls[key].updateValueAndValidity();
        }
        this.imageList = [];
        this.modalService.success({
          nzTitle: '信息提示',
          nzContent: '您的问题提交成功，我们将尽快为您处理!'
        });
      });
    }
  }

  constructor(
    private fb: FormBuilder,
    private modalService: NzModalService,
    private workOrderService: WorkOrderService,
    private msg: NzMessageService,
    @Inject(API_CONFIG) private uri: string
  ) { }

  ngOnInit(): void {
    this.uploadUrl = this.uri + '/custom/upload/work-order';
    let ticket = window.sessionStorage['ticket'];
    this.headers = { 'Authorization': 'BasicAuth ' + ticket };
    this.validateForm = this.fb.group({
      urgent: [null, [Validators.required]],
      content: [null, [Validators.required]],
      phone: [null, [Validators.required]]
    });
  }

}
